package com.epfresh.adapter;

import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.bean.OftenListCategoryBean;
import com.epfresh.global.BaseFragment;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import multitype.ItemViewBinder;

/**
 * Author: Chen
 * Date: 2019/3/11
 * Desc:
 */
public class ViewBinderOftenList extends ItemViewBinder<OftenListCategoryBean, ViewBinderOftenList.ViewHolder> {
    private BaseFragment baseFragment;
    private List<BaseFragment> fragmentList;
    private List<String> tabTitles;
    private MyFragmentPagerAdapter pagerAdapter;
    private boolean show = false;
    private boolean updateTabBg = false;

    public ViewBinderOftenList(BaseFragment baseFragment) {
        this.baseFragment = baseFragment;
    }

    public void setFragmentList(List<BaseFragment> fragmentList) {
        this.fragmentList = fragmentList;
    }

    public void setTabTitles(List<String> tabTitles) {
        this.tabTitles = tabTitles;
    }

    @NonNull
    @Override
    protected ViewHolder onCreateViewHolder(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
        View itemView = inflater.inflate(R.layout.item_often_list, parent, false);
        return new ViewHolder(itemView);
    }

    @Override
    protected void onBindViewHolder(@NonNull final ViewHolder holder, @NonNull OftenListCategoryBean item) {

        if (updateTabBg) {
            if (holder.tab_bg.getVisibility() == View.GONE && show) {
                holder.tab_bg.setVisibility(View.VISIBLE);
                show = true;
            }
            if (holder.tab_bg.getVisibility() == View.VISIBLE && !show) {
                holder.tab_bg.setVisibility(View.GONE);
                show = false;
            }
            updateTabBg = false;
        } else {

            if (pagerAdapter == null) {
                pagerAdapter = new MyFragmentPagerAdapter(baseFragment.getChildFragmentManager());
                holder.often_vp.setAdapter(pagerAdapter);
                holder.often_tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                    @Override
                    public void onTabSelected(TabLayout.Tab tab) {
                        holder.often_vp.setCurrentItem(tab.getPosition());
                    }

                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {

                    }

                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {

                    }
                });
                holder.often_vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        holder.often_tab_layout.getTabAt(position).select();
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }

            if (isInit) {
                holder.often_vp.setOffscreenPageLimit(item.getTopCategory().size() - 1);
                holder.often_tab_layout.removeAllTabs();
                addTabs(holder, tabTitles);
                pagerAdapter.setDataInfo(fragmentList);
                pagerAdapter.notifyDataSetChanged();
                holder.often_vp.setCurrentItem(0);
                setIndicatorWidth(holder.often_tab_layout);
                isInit = false;
            }
        }
    }

    private boolean isInit = true;

    public void setInit(boolean init) {
        isInit = init;
    }

    private void addTabs(ViewHolder holder, List<String> tabTitles) {
        for (String tabTitle : tabTitles) {
            holder.often_tab_layout.addTab(holder.often_tab_layout.newTab().setText(tabTitle));
        }
    }

    public void setTabBgShow(boolean show) {
        if (this.show != show) {
            this.show = show;
            updateTabBg = true;
            getAdapter().notifyDataSetChanged();
        }
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        private TabLayout often_tab_layout;
        private ViewPager often_vp;
        private View tab_bg;

        ViewHolder(View itemView) {
            super(itemView);

            often_tab_layout = itemView.findViewById(R.id.often_tab_layout);
            often_vp = itemView.findViewById(R.id.often_vp);
            tab_bg = itemView.findViewById(R.id.tab_bg);
        }
    }


    class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
        private List<BaseFragment> fragmentList;


        MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
            fragmentList = new ArrayList<>();
        }

        private void setDataInfo(List<BaseFragment> fragmentList) {
            this.fragmentList.clear();
            this.fragmentList.addAll(fragmentList);
        }


        @Override
        public Fragment getItem(int position) {
            return fragmentList == null ? null : fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList == null ? 0 : fragmentList.size();
        }

        @Override
        public int getItemPosition(@NonNull Object object) {
            return PagerAdapter.POSITION_NONE;
        }
    }


    /**
     * 设置tab指示器的长度(随tab的长度)
     *
     * @param tabLayout
     */
    private void setIndicatorWidth(final TabLayout tabLayout) {
        tabLayout.post(new Runnable() {

            @Override
            public void run() {
                try {
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);
                    int dpMargin = LocalDisplay.dp2px(10);
                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);
                        TextView mTextView = (TextView) mTextViewField.get(tabView);
                        mTextView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                        tabView.setPadding(0, 0, 0, 0);
                        int width;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = dpMargin;
                        params.rightMargin = dpMargin;
                        tabView.setLayoutParams(params);
                        tabView.invalidate();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

}
